package web;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Dealer;
import model.Deck;
import model.Game;
import model.Hand;
import model.Player;
import model.Pot;
import model.Round;

/**
 * Servlet implementation class NewRoundServlet
 */
@WebServlet("/NewRoundServlet")
public class NewRoundServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewRoundServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext sc = getServletContext();
		Game game = (Game) sc.getAttribute("game");
		Player[] playerList = (Player[]) sc.getAttribute("playerList");
		Dealer dealer = (Dealer) sc.getAttribute("dealer");
		
		ArrayList<Player> playingList = new ArrayList<Player>();
		sc.setAttribute("playingList", playingList);
		
		for(Player player : playerList){	
			if(player!=null){
				player.setHand(new Hand());	//transfer all the players scattered in the table into an arraylist
				player.resetAllFields();
				playingList.add(player);	//adds a new hand to the transfered player
			}
		}
		
		dealer.setDeck(new Deck());
		dealer.shuffle();
		
		dealer.assignBlinds(playingList);
		dealer.dealCards(playingList);
		Round round = new Round(playingList);
		int initialPotAmount = round.collectBlinds(playingList, game.getBigBlind());	//returns the initial pot collected from the small and big blinds
		Pot pot = new Pot(initialPotAmount);
		round.setPot(pot);
		round.determineNextToAct(dealer);
		game.setRound(round);
		
		sc.setAttribute("round", round);	//throws the newly created round object in the pot
		sc.setAttribute("pot", pot);	//throws the pot into the servlet context
		System.out.println("round started");
	}
}
